package com.libbase.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Shader;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;

public class FadeRecyclewView extends RecyclerView {
    private static final String TAG = "FadeRecyclewView";
    private Paint paint;
    private int height;
    private int width;
    private LinearGradient linearGradient;
    private PorterDuffXfermode xfermode;

    private float spanPixel = 0.5f;

    private int orientation = ORIENTATION.HORIZONTAL;

    public FadeRecyclewView(Context context) {
        this(context, null);
    }

    public FadeRecyclewView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public FadeRecyclewView(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        init();
    }

    private void init() {
        paint = new Paint();
        paint.setAntiAlias(true);
        xfermode = new PorterDuffXfermode(PorterDuff.Mode.DST_IN);
        paint.setXfermode(xfermode);
    }

    /**
     * 设置渐变的位置
     *
     * @param spanPixel
     */
    public void setSpanPixel(int spanPixel) {
        this.spanPixel = spanPixel;
        postInvalidate();
    }

    /**
     * 设置模式
     *
     * @param mode
     */
    public void setOrientationMode(int mode) {
        this.orientation = mode;
        postInvalidate();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        height = h;
        width = w;
        if (orientation == ORIENTATION.HORIZONTAL) {
            linearGradient = new LinearGradient(0, 0, width / 2, 0,
                    new int[]{0x00000000, 0xff000000, 0xff000000}, new float[]{0, spanPixel, 1f}, Shader.TileMode.MIRROR);
        } else if (orientation == ORIENTATION.VERTICAL) {
            linearGradient = new LinearGradient(0, 0, 0, height / 2,
                    new int[]{0x00000000, 0xff000000, 0xff000000}, new float[]{0, spanPixel, 1f}, Shader.TileMode.MIRROR);
        }
        paint.setShader(linearGradient);
    }

    @Override
    public void draw(Canvas canvas) {
        int layoutId = canvas.saveLayer(0, 0, width, height, null, Canvas.ALL_SAVE_FLAG);
        super.draw(canvas);
        canvas.drawRect(0, 0, width, height, paint);
        canvas.restoreToCount(layoutId);
    }

    public final class ORIENTATION {
        public static final int VERTICAL = 1; // 竖向
        public static final int HORIZONTAL = 2; // 横向
    }
}
